<template xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
  <div id="askAnswer">
    <p>
      Ask a yes/no question:
      <input v-model="question">
      <!--<input v-bind:value="question" v-on:input="question = $event.target.value">-->
    </p>
    <p>{{ answer }}</p>
    <input
      v-model="newTodoText"
      v-on:keyup.enter="addNewTodo"
      placeholder="Add a todo"
    >
    <button v-on:click="shuffle">Shuffle</button>
    <transition-group name="flip-list" tag="ul">
      <li
        is="TodoItem"
        v-for="(todo, index) in todos"
        v-bind:title="todo"
        v-on:remove="todos.splice(index, 1)"
        v-bind:key="todo"
      ></li>
    </transition-group>
    <select v-model="selected">
      <option v-for="option in options" v-bind:value="option.value">
        {{ option.text }}
      </option>
    </select>
    <span>Selected: {{ selected }}</span>
  </div>
</template>

<script>
  import _ from 'lodash'
  import axios from 'axios'
  import TodoItem from '@/components/test/widget/TodoItem'
  export default {
    name: 'askAnswer',
    components: {
      TodoItem
    },
    data () {
      return {
        question: '',
        answer: 'I cannot give you an answer until you ask a question!',
        newTodoText: '',
        todos: [
          'Do the dishes',
          'Take out the trash',
          'Mow the lawn'
        ],
        selected: 'A',
        options: [
          { text: 'One', value: 'A' },
          { text: 'Two', value: 'B' },
          { text: 'Three', value: 'C' }
        ]
      }
    },
    watch: {
      // 如果 question 发生改变，这个函数就会运行
      question: function (newQuestion) {
        console.log('ask answer')
        this.answer = 'Waiting for you to stop typing...'
        this.getAnswer()
      }
    },
    methods: {
      getAnswer: _.debounce(
        function () {
          var vm = this
          console.log('ask answer')
          if (this.question.indexOf('?') === -1) {
            vm.answer = 'Questions usually contain a question mark. ;-)'
            return
          }
          vm.answer = 'Thinking...'
          axios.get('https://yesno.wtf/api')
            .then(function (response) {
              vm.answer = _.capitalize(response.data.answer)
            })
            .catch(function (error) {
              vm.answer = 'Error! Could not reach the API. ' + error
            })
        },
        // 这是我们为用户停止输入等待的毫秒数
        1
      ),
      addNewTodo: function () {
        this.todos.push(this.newTodoText)
        this.newTodoText = ''
      },
      shuffle: function () {
        this.todos = _.shuffle(this.todos)
      }
    }
  }
</script>
<style>
  .flip-list-move {
    transition: transform 1s;
  }
</style>
